package com.itheima.reggie_test.web;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie_test.common.Result;
import com.itheima.reggie_test.entity.Employee;
import com.itheima.reggie_test.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @ auther: 小熊
 * @ date:2022/12/14 11:36
 * @Todo :
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    IEmployeeService employeeService;

    /**
     * 登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {

        //获取对象
        String username = employee.getUsername();
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(wrapper);

        //对象是否存在
        if (emp == null) {
            //返回Result对象，结束本次请求
            return Result.error("用户名不存在");
        }

        //密码是否正确
        String password = employee.getPassword();
        //数据库中存储的是MD5加密过后的数据，所以需进行转换
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!emp.getPassword().equals(password)) {
            return Result.error("密码不正确");
        }

        //账户是否被冻结
        if (emp.getStatus() == 0) {
            return Result.error("账户被冻结");
        }

        //存储用户信息id
        request.getSession().setAttribute("empId", emp.getId());
        return Result.success(emp);
    }


    /**
     * 退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("empId");
        return Result.success("退出成功");
    }

    /**
     * 添加
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public Result add(HttpServletRequest request,@RequestBody Employee employee){
        //0、检查数据，哪些是需要处理的
        //0.1: 密码使用默认的123456 ， 需要加密 DigestUtils.md5DigestAsHex
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //0.2： status 不需要处理，数据库默认是1
        //0.3： create_time 和 update_time ,设置为当前系统时间  LocalDateTime.now()
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
        //0.4： create_user 和 update_user 创建人和修改人，应该是当前登陆人，从session中获取
//        Long empId = (Long) request.getSession().getAttribute("empId");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);
        //1、调用业务层保存 employee数据
        employeeService.save(employee);
        //2、返回结果R
        return Result.success("添加成功");
    }


    /**
     * 分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page> queryAllAndToPage(int page,int pageSize,String name){
        // 进行带条件的分页查询， employeeService.page(pageInfo,qw);
        Page pageInfo = new Page(page, pageSize);
        //employeeService.page(pageInfo, qw);
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Employee::getName,name);
        wrapper.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo,wrapper);

        // 通过pageInfo对象获取分页结果  1、List<> 集合 records  2、总记录数 total
        return Result.success(pageInfo);
    }

    @PutMapping
    public Result update(HttpServletRequest request,@RequestBody Employee employee){
        //1、修改员工数据 update_time
//        employee.setUpdateTime(LocalDateTime.now());
        //2、修改员工数据 update_user 从sesion中获取员工id
        Long empId = (Long) request.getSession().getAttribute("empId");
//        employee.setUpdateUser(empId);
        //3、调用业务层修改员工信息 updateById()
        employeeService.updateById(employee);

        return Result.success("修改成功");

    }

    @GetMapping("/{id}")
    public Result<Employee> queryOne(@PathVariable Long id){
        Employee emp = employeeService.getById(id);
        if (emp==null){
            return Result.error("查无此人");
        }
        return Result.success(emp);
    }
}
